import React from 'react';
import { Link } from 'react-router-dom';
import SelectAddress from './../../common/select_address/index.js';
import { Dialog ,Form,Radio,Checkbox } from 'element-react';
import { DatePicker } from 'element-react';
import CascadeMultiSelect from 'uxcore/lib/CascadeMultiSelect';
import { Select,Table,Pagination,Tag,Icon } from 'element-react';
import { Input,Button,MessageBox,Layout } from 'element-react';
import axios from 'axios';
import Top from '../../top/index.js';
import Nav from '../../nav/index.js';
import './index.css';
import util from '../../../assets/js/util.js';

class ServiceHouseReceive extends React.Component{
	constructor(props) {
		super(props)
		this.state = {
			 	dialogVisible3: false,
			 	page:'',
			 	type:1,
                pageStart:'',
                pageEnd:'',
				exportValue:1,
				exportFields:["分站", "服务亭", "订单号", "客户手机号", "总重量", "订单支付金额", "订单状态", "品类重量", "品类"],
                substation: [{label:'请选择',value:0}],//分站
                pkgstation: [{label:'请选择',value:0}],//分拣中心
                svcstation: [{label:'请选择',value:0}],//服务亭
				totalPage:'', //总页数
				curPage:1, //当前页
				total:0,
				
				payTypeOptions: [
				{
					value: '',
					label: '请选择'
			    },{

					value: '1',
					label: '现金支付'
				}, {
					value: '2',
					label: '银行卡转帐'
				}],
				payTypeValue:'', //支付方式选中值
				orderStatusOptions: [
				{
					value: '',
					label: '请选择'
			    },
				{
					value: '2',
					label: '已支付'
				},{
					value: '3',
					label: '已交货'
				},{
					value: '5',
					label: '已销售'
				},{
					value: '6',
					label: '已取消'
				}],
				orderStatusValue:'', //订单状态选中值
				//导出字段数据
				checkboxData:[{ 
					name:'分站',
					type:'substationName'
				},{
					name:'服务亭',
					type:'houseName'
				},{
					name:'订单号',
					type:'orderNum'
				},{
					name:'客户手机号',
					type:'userMobile'
				},{
					name:'总重量',
					type:'netWeight'
				},{
					name:'订单支付金额',
					type:'recyclePrice'
				},{
					name:'订单状态',
					type:'status'
				},{
	                name:'品类重量',
	                type:'weight'
                },{
	                name:'品类',
	                type:'recycleTypeTitle'
                }],
				recycleOrderList: [], //表格数据
				subId: 0,
                pkgId: 0,
                houseId: 0,
                subchecking: true,
	            pkgchecking: true,
	            subIndex: 0,
	            pkgIndex: 0,
				startDate: null,//开始时间
				endDate: null,//结束时间
				recyclePriceStart:'',//订单金额开始
				recyclePriceEnd:'',//订单金额结束
				orderNum:'',//订单号
				netWeight:'',
				columns: [
				 	{
				 		label: "序号",
						width: 150,
			        	type: 'index'
			        },
					{
						label: "分站",
						prop: "substationName",
						width: 160,
						render: function(data){
						return (
						<span>
							<span>{data.substationName}</span>
						</span>)
						}
					},
					{
						label: "服务亭",
						prop: "nickName",
						width: 160,
						render: function(data){
						return (
							<span>
								<span>{data.nickName}</span>
							</span>
						)
						}
					},
					{
						label: "订单号",
						prop: "orderNum",
						width: 260,
						render: function(data){
						return (
							<span>
								<span title={data.orderNum}>{data.orderNum}</span>
							</span>
						)
						}
					},{
						label:'收货时间',
						prop:'ctime',
						width: 160,
						render: function(data){
						return (
							<span>
								<span>{util.getDateTime(data.ctime)}</span>
							</span>
						)
						}
					},{
						label: "客户手机号",
						prop: "userMobile",
						width: 160,
						render: function(data){
						return (
							<span>
								<span>{data.userMobile}</span>
							</span>
						)
						}
					},
					{
						label: "总重量(kg)",
						prop: "netWeight",
						width: 160,
						render: function(data){
						return (
							<span>
								<span>{data.netWeight/1000}</span>
							</span>
						)
						}
					},
					{
						label: "订单支付金额(元)",
						prop: "recyclePrice",
						width: 120,
						render: function(data){
						return (
							<span>
								<span>{data.recyclePrice/100}</span>
							</span>
						)
						}
					},
					{
						label: "订单状态",
						prop: "payType",
						width: 160,
						render: function(data){
						return (
							<span>
								<span>{util.setOrderStatus(data.status)}</span>
							</span>
						)
						}
					},
					{
						label: "操作",
						prop: "operate",
						width: 160,
						render: function(data){
							return (
								<span>
									<Link to = {'/viewReceive/' + data.orderNum} target="_blank"> 查看 </Link>
									<Link to = {'/trackSend/' + data.orderNum} target="_blank">{data.status=='5'?'':'轨迹'}</Link>
								</span>
							)
						}
					}
				]
		}
		this.substationChange = this.substationChange.bind(this);
        this.pkgstationChange = this.pkgstationChange.bind(this);
        this.svcstationChange = this.svcstationChange.bind(this);
        this.selectCheckbox = this.selectCheckbox.bind(this);
	}

	componentDidMount() {
		this.getData(1);
		this.getAllId();
	}

	// 获取所有分站
    getAllId() {
        //数据获取
        axios.post('count/count/subsandpkgs').then((res) => {
            // console.log(res);
            //分站列表
            const substation = new Array(res.data.data.length);

            res.data.data.forEach((item, index) => {
                substation[index] = {
                    value: item.id,
                    label: item.name
                }
            });
            substation.unshift({value:"",label:"请选择分站"});
            this.setState({substation:substation})
          
        }).catch((err) => {
            console.log(err);
        });

    }

	//请求列表数据
	getData(curPage){
		var params = new URLSearchParams();

		let startDate,endDate;

		if(this.state.startDate){
			startDate = util.formatDate(this.state.startDate);
		}else{
			startDate = '';
		}
		if(this.state.endDate){
			endDate = util.formatDate(this.state.endDate);
		}else{
			endDate = '';
		}
		params.append('substationId',this.state.subId)
		params.append('packageId',this.state.pkgId);
		params.append('houseId',this.state.houseId);
		params.append('startDate', startDate);
		params.append('endDate', endDate);
		params.append('status', this.state.orderStatusValue);
		params.append('orderNum', this.state.orderNum);
		params.append('payType', this.state.payTypeValue);
		params.append('recyclePriceStart', this.state.recyclePriceStart);
		params.append('recyclePriceEnd', this.state.recyclePriceEnd);
		params.append('page', curPage);
		params.append('size', 20);

		axios.post('/count/countranking/getRecycleOrderRecycle', params).then((data) => {
			console.log(data)
			let res = data.data;
			if (res.code == 0) {
				this.setState({
					curPage:res.data.curPage,
					totalPage:res.data.totalPage,
					total:res.data.total,
					recycleOrderList: res.data.recycleOrderList,
					selectByPrimaryKey:res.data.selectByPrimaryKey
				})
			}else if(res.code == -111){
				MessageBox.alert(res.msg);
			} else {
				this.props.history.push('/login')
			}
		}).catch((e) => {
			console.log(e)
		})
	}

	onChange(key,value) {
		this.state[key] = value;
		this.forceUpdate();
	}

    // 选择全部记录还是当前页记录
	onExportChange(e) {
		this.setState({
			exportValue: e
		});
	}

    //分站change事件
    substationChange = (val, option) => {
        this.setState({subId: val});
        var params = new URLSearchParams();
        params.append('subId', val);
        axios.post('count/count/selectpkgsbysubid', params)
            .then((res) => {
                console.log(res);
                const pkgstation = new Array(res.data.data.length);
                res.data.data.forEach((item, index) => {
                    pkgstation[index] = {
                        value: item.id,
                        label: item.siteName
                    }
                });
                pkgstation.unshift({value:"",label:"请选择分拣中心"});
               
                this.setState({pkgstation: pkgstation})
            })
            .catch((err) => {
                console.log(err)
            });
    };

    //分拣中心change事件
    pkgstationChange = (val, option) => {
       
        this.setState({pkgId: val});
        var params = new URLSearchParams();
        params.append('pkgId', val);
        axios.post('count/count/selecthousesbypkgid', params)
            .then((res) => {
                console.log(res);
                const svcstation = new Array(res.data.data.length);
                res.data.data.forEach((item, index) => {
                    svcstation[index] = {
                        value: item.id,
                        label: item.nickname
                    }
                });

                svcstation.unshift({value:"",label:"请选择服务亭"});
                this.setState({svcstation: svcstation})
            })
            .catch((err) => {
                console.log(err)
            });
    };

    //服务亭change事件
    svcstationChange = (val, option) => {
        this.setState({houseId: val});
    };

	//搜索
	handClick(event) {
		event.preventDefault();
		this.getData(1);
	}

	//选择导出字段
	selectCheckbox(e){
		this.setState({
			exportFields: e
		})
	}

	//确定导出
	exportSure(){
		var _page = '';
		var fileds = [];
		
		let pageEnd='';

		let startDate,endDate;

		if(this.state.startDate){
			startDate = util.formatDate(this.state.startDate);
		}else{
			startDate = '';
		}
		if(this.state.endDate){
			endDate = util.formatDate(this.state.endDate);
		}else{
			endDate = '';
		}

		if(this.state.exportValue == 1){
			_page = '';
		}else if(this.state.exportValue == 2){
			_page = this.state.curPage;
		}else if(this.state.exportValue == 3){
            _page=this.state.pageStart;
            pageEnd = this.state.pageEnd;
        }

		let checkboxData = this.state.checkboxData;
		let exportFields = this.state.exportFields;
		checkboxData.forEach((item,index)=>{
			exportFields.forEach((subItem,subIndex)=>{
				if(item.name == subItem){
					fileds.push(item.type)
				}
			})
		})

		if(fileds.length < 2) return alert('请至少勾选两项');


		window.open('/count/countranking/getRecycleOrderRecycleExcel?page=' + _page +'&pageEnd=' + pageEnd + '&fields=' + fileds.join(',')+'&substationId='+this.state.subId+'&houseId='+this.state.houseId+'&startDate='+startDate+'&endDate='+endDate+'&status='+this.state.orderStatusValue+'&orderNum='+this.state.orderNum+'&payType='+this.state.payTypeValue+'&recyclePriceStart='+this.state.recyclePriceStart+'&recyclePriceEnd='+this.state.recyclePriceEnd);

	}

	//导出弹框
	export(){
		this.setState({
			dialogVisible3: true
		})
	}

	//请求分页数据
	currentPageChange(value){ 
		//请求当前页
		this.getData(value)
	}

	render(){
		return (
			<div className="main_receive">
			    <Top/>
                <Nav serviceReceive='active'/>
				<div className="container_receive">
					<div className="top_top1">
						<Layout.Row gutter="0" style={{marginTop:'40px'}}>
							<div className="source boxone">
								<div className="block">
									<span className="demo">日期：</span>
									<DatePicker
										value={this.state.startDate}
										placeholder="选择日期"
										onChange={date=>{
											this.setState({startDate: date})
										}}
									/>
									<span className="demo margin">至 </span>
									<DatePicker
										value={this.state.endDate}
										placeholder="选择日期"
										onChange={date=>{
											this.setState({endDate: date})
										}}
									/>
								</div>
							</div>
							<div className="box">
							   <span className="demo">分站：</span>
								 <SelectAddress
	                                value='请选择分站'
	                                options={this.state.substation}
	                                clsname="slct_substation"
	                                selChange={this.substationChange}
	                            ></SelectAddress> 
	                        </div>
							<div className="box">
							    <span className="demo">分拣中心：</span>
								 <SelectAddress
	                                value='请选择分拣中心'
	                                options={this.state.pkgstation}
	                                clsname='slct_pkgstation'
	                                selChange={this.pkgstationChange}
	                            ></SelectAddress>
							</div>
							<div className="box">
							     <span className="demo">服务亭：</span>
								 <SelectAddress
	                                value='请选择服务亭'
	                                options={this.state.svcstation}
	                                clsname='slct_svcstation'
	                                selChange={this.svcstationChange}
	                            >
	                            </SelectAddress>
							</div>

							<div className="box">	
								<span className="demo">订单状态：</span>   
								<Select value={this.state.orderStatusValue} onChange={this.onChange.bind(this,'orderStatusValue')}>
									{
										this.state.orderStatusOptions.map(el => {
										return <Select.Option key={el.value} label={el.label} value={el.value} />
										})
									}
								</Select>
							</div>
						
							<div className="box">	
								<span className="demo">支付方式：</span>   
								<Select value={this.state.payTypeValue} className="" onChange={this.onChange.bind(this,'payTypeValue')}>
									{
										this.state.payTypeOptions.map(el => {
										return <Select.Option key={el.value} label={el.label} value={el.value} />
										})
									}
								</Select>
							</div>

							<div className="box">  
								<span className = "demo" > 支付金额：</span>
								<div className="write">
									<Input placeholder = "" className="bg_color" maxlength="10" value={this.state.recyclePriceStart} onChange={this.onChange.bind(this,'recyclePriceStart')} />
								</div>
								<span className="demo margin">至</span>
								<div className="write">
									<Input placeholder = "" className="bg_color" maxlength="10" value={this.state.recyclePriceEnd} onChange={this.onChange.bind(this,'recyclePriceEnd')} />
								</div>
								<span className = "demo">元</span>
							</div>
							<div className="box">
							    <span className="demo">订单号：</span>   
							    <Input placeholder = "" className="" 
									style={{width:'150px'}}
							    	onChange={this.onChange.bind(this,'orderNum')}/>
							</div>
							<div className="box">
							    <Button type="info" className="out1" onClick={this.export.bind(this)} >
									<i class="el-icon-upload mr-6"></i>导出
								</Button>
								<Button type = "info" className="search0" style={{marginRight:'15px'}} onClick={this.handClick.bind(this)}>
									<i class="el-icon-search mr-6"></i>搜索 
								</Button>
							</div>
						</Layout.Row>
							
		
						<div className="write write_4 sar">
						
						  <Dialog title = "导出" visible={ this.state.dialogVisible3 }
								onCancel={ () => this.setState({ dialogVisible3: false }) }>
							
								<Dialog.Body>
									<Form model={this.state.form}>

										<Form.Item label="导出为" labelWidth="120">
											<Select value="1" placeholder="请选择导出方式">
												<Select.Option label="Excel" value="1"></Select.Option>
											</Select>
										</Form.Item>
										<Form.Item>
											<Radio value="1" checked={this.state.exportValue === 1} 
											onChange={this.onExportChange.bind(this)}>全部记录</Radio>
											<Radio value="2" checked={this.state.exportValue === 2} 
											onChange={this.onExportChange.bind(this)}>当前页记录</Radio>
											<Radio value="3" checked={this.state.exportValue === 3}
                                               onChange={this.onExportChange.bind(this)}>
                                            <span >从</span>
                                            <Input className="exportInput"  onChange={(el)=>{this.setState({pageStart:el})}}/><span>至</span>
                                            <Input className="exportInput"  onChange={(el)=>{this.setState({pageEnd:el})}}/><span>页</span>
                                            </Radio>
										</Form.Item>

										<Form.Item label="导出字段" labelWidth="120">
											
										</Form.Item>

										<Form.Item>
											<div className="check is-checked">
												<Checkbox.Group value={this.state.exportFields} onChange={ this.selectCheckbox.bind(this) }>
													{
														this.state.checkboxData.map((item,index)=>{
															return <Checkbox key={index} label={item.name}></Checkbox>
														})
													}
											    </Checkbox.Group>
										    </div>
										</Form.Item>
									</Form>
								</Dialog.Body>

                            <Dialog.Footer className="dialog-footer">
                                <Button className="can" onClick={ () => this.setState({ dialogVisible3: false }) }>取 消</Button>
                                <Button className="sur" type="primary" onClick={ this.exportSure.bind(this) }>确 定</Button>
        					</Dialog.Footer>
      					  </Dialog>
      						
					    </div>
					</div>

					
					<div className="table_3 tablebar">
						<Table
							style={{width: '100%'}}
							columns={this.state.columns}
							data={this.state.recycleOrderList}
							total={this.state.total}
							border={true}
							highlightCurrentRow={true}
						/>
						{<Pagination layout="total,prev, pager, next, jumper" 
						total={this.state.total}
						pageSize={20} 
						currentPage={this.state.curPage}
						onCurrentChange={this.currentPageChange.bind(this)}
						/>}
					</div>
				</div>
			</div>
		);
	}

}
export default ServiceHouseReceive;